package com.lilihub.miaosha.service;

import com.lilihub.miaosha.domain.MiaoshaOrder;
import com.lilihub.miaosha.domain.MiaoshaUser;
import com.lilihub.miaosha.domain.OrderInfo;
import com.lilihub.miaosha.redis.MiaoshaKey;
import com.lilihub.miaosha.util.MD5Util;
import com.lilihub.miaosha.util.UUIDUtil;
import com.lilihub.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @BelongsProject: miaosha
 * @BelongsPackage: com.lilihub.miaosha.service
 * @Author: LiYing
 * @CreateTime: 2021-04-27 12:52
 * @Description:
 */
@Service
public class MiaoshaService {


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisService redisService;



    //减库存 下订单 写入秒杀订单
    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goods) {

        //减库存
        boolean success = goodsService.reduceStock(goods);

        if (success){
            //下订单  order_info,miaosha_order
            return orderService.createOrder(user,goods);
        }else{

            //如果库存已经秒杀完了，做一个标记
            setGoodsOver(goods.getId());
            return null;
        }
    }


    //客户端轮询，是否秒杀成功
    public long getMiaoshaResult(Long userId, long goodsId) {

        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);

        if (order != null ){  //秒杀成功
            return order.getOrderId();
        }else{

            boolean isOver = getGoodsOver(goodsId);
            if (isOver){
                return -1;
            }else{
                return 0;
            }
        }
    }

    private void setGoodsOver(Long goodsId) {

        redisService.set(MiaoshaKey.isGoodsOver, ""+goodsId, true);

    }
    private boolean getGoodsOver(long goodsId) {

        return redisService.exists(MiaoshaKey.isGoodsOver, ""+goodsId);
    }

    //秒杀收到请求，先验证PathVariable
    public boolean checkPath(MiaoshaUser user, long goodsId, String path) {

        if (user == null || path == null){
            return false;
        }

        String pathOld = redisService.get(MiaoshaKey.getMiaoshaPath, "" + user.getId() + "_" + goodsId, String.class);

        return path.equals(pathOld);

    }


    public String createMiaoshaPath(MiaoshaUser user, long goodsId) {

        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");

        redisService.set(MiaoshaKey.getMiaoshaPath,""+ user.getId() + "_" + goodsId,str);

        return str;
    }


    //1 添加生成验证码的接口
    public BufferedImage createMiaoshaVerifyCode(MiaoshaUser user, long goodsId) {

        if (user == null || goodsId <= 0){
            return null;
        }

        int width = 80;
        int height = 32;

        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);

        Graphics g = image.getGraphics();
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0,0,width,height);
        g.setColor(Color.black);
        g.drawRect(0,0,width-1,height-1);

        Random rdm = new Random();
        for (int i = 0; i< 50;i++){
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x,y,0,0);
        }

        String verifyCode = createVerifyCode(rdm);
        g.setColor(new Color(0,100,0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode,8,24);
        g.dispose();

        int rnd = calc(verifyCode);
        redisService.set(MiaoshaKey.getMiaoshaVerifyCode,user.getId() +","+goodsId,rnd);
        return image;
    }


    //2 在获取秒杀路径的时候，验证验证码
    public boolean checkVerifyCode(MiaoshaUser user, long goodsId, int verifyCode) {

        if (user == null || goodsId <= 0){
            return false;
        }

        Integer codeOld = redisService.get(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, Integer.class);

        if (codeOld == null || codeOld - verifyCode != 0){
            return false;
        }
        redisService.delete(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId);
        return true;

    }


    private int calc(String exp) {

        try {

            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (int) engine.eval(exp);

        }catch (Exception e){

            e.printStackTrace();
            return 0;

        }

    }

    private static char[] ops = new char[]{'+','-','*'};
    // + - *
    private String createVerifyCode(Random rdm) {

        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);

        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];

        String exp = "" + num1 + op1 + num2 + op2 + num3;

        return exp;
    }


}
